package com.pig4cloud.pig.ads.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.ads.pig.mapper.AdvMapper;
import com.pig4cloud.pig.ads.pig.mapper.AdvertiserMapper;
import com.pig4cloud.pig.ads.service.AdUserAdverService;
import com.pig4cloud.pig.ads.service.ToutiaoDistrictService;
import com.pig4cloud.pig.ads.service.TtAccesstokenService;
import com.pig4cloud.pig.api.entity.ToutiaoDistrict;
import com.pig4cloud.pig.ads.pig.mapper.ToutiaoDistrictMapper;
import com.pig4cloud.pig.common.core.util.R;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class ToutiaoDistrictServiceImpl extends ServiceImpl<ToutiaoDistrictMapper, ToutiaoDistrict> implements ToutiaoDistrictService {

	private final ToutiaoDistrictMapper toutiaoDistrictMapper;

	private final TtAccesstokenService ttAccesstokenService;

	private final AdUserAdverService adUserAdverService;

	private final AdvMapper advMapper;

	@Autowired
	private AdvertiserMapper advertiserMapper;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;




	@Override
	public void makeDataDistrict() {
		String content = readFileContent("C:\\Users\\Administrator\\Downloads\\data_20190222\\city.json");
		JSONObject obj = JSON.parseObject(content);

		List<ToutiaoDistrict> list = new ArrayList<>();
		for (String key :obj.keySet()){
			JSONObject item = obj.getJSONObject(key);

			ToutiaoDistrict objItem = new ToutiaoDistrict(
					item.getInteger("id"),
					item.getInteger("parent"),
					item.getInteger("level"),
					item.getString("children").replace("[","").replace("]", ""),
					item.getString("name"),
					0
			);
			list.add(objItem);
		}
		boolean result = this.saveBatch(list);
		System.out.println("++++++++++++++++++++++>>>" + result);
	}

	@Override
	public void makeDataDistrictBusiness() {
		String content = readFileContent("C:\\Users\\Administrator\\Downloads\\data_20190222\\district_business.json");
		JSONObject obj = JSON.parseObject(content);

		String listStr= obj.getJSONObject("data").getString("list");
		List<Map> mapList = JSON.parseArray(listStr, Map.class);

		List<ToutiaoDistrict> list = new ArrayList<>();
		List<ToutiaoDistrict> uptList = new ArrayList<>();
		for (Map<String, Object> item : mapList){
			String regionLevel = (String) item.get("region_level");
			if (regionLevel.equals("REGION_LEVEL_BUSINESS_DISTRICT")){
				ToutiaoDistrict objItem = new ToutiaoDistrict(
						(Integer) item.get("id"),
						(Integer)item.get("parent_id"),
						4,
						"",
						(String) item.get("name"),
						0
				);
				list.add(objItem);
			}

			if (regionLevel.equals("REGION_LEVEL_CITY")){
				ToutiaoDistrict objItem = toutiaoDistrictMapper.selectById((Integer)item.get("id"));
				if (objItem == null){
					System.out.println(">>>>>>>>>>>>>>" + item.get("id"));
				}else{
					objItem.setProviceCapital(1);
					uptList.add(objItem);
				}
			}
		}
		boolean result = this.saveBatch(list);
		boolean result1 = this.saveOrUpdateBatch(uptList);
		System.out.println("++++++++++++++++++++++>>>" + result + "|" + result1);
	}

	@Override
	public List<ToutiaoDistrict> listByParentId(Integer parentId, Integer level) {
		List<ToutiaoDistrict> list = toutiaoDistrictMapper.listByParentId(parentId, level);
		return list;
	}

	@Override
	public List<ToutiaoDistrict> provinceCapital(Integer provinceId) {
		List<ToutiaoDistrict> list =toutiaoDistrictMapper.provinceCapital(provinceId);
		return list;
	}

	@Override
	public List<ToutiaoDistrict> searchCity(String searchStr) {
		return toutiaoDistrictMapper.searchCity(searchStr);
	}

	@Override
	public List<ToutiaoDistrict> citiesByLevel(Integer level) {
		return toutiaoDistrictMapper.citiesByLevel(level);
	}

	@Override
	public List<ToutiaoDistrict> nameByIds(String ids) {
		if (StringUtils.isBlank(ids))
			return null;
		return toutiaoDistrictMapper.nameByIds(ids);
	}


	private static String readFileContent(String fileName) {
		File file = new File(fileName);
		BufferedReader reader = null;
		StringBuffer sbf = new StringBuffer();
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempStr;
			while ((tempStr = reader.readLine()) != null) {
				sbf.append(tempStr);
			}
			reader.close();
			return sbf.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return sbf.toString();
	}

	private static String readFileContent(File file) {
		BufferedReader reader = null;
		StringBuffer sbf = new StringBuffer();
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempStr;
			while ((tempStr = reader.readLine()) != null) {
				sbf.append(tempStr);
			}
			reader.close();
			return sbf.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return sbf.toString();
	}

	//ToutiaoDistrict obj = toutiaoDistrictMapper.selectById(1);


	@Override
	public R cities() {
		InputStream is = this.getClass().getClassLoader().getResourceAsStream("city.json");
		byte[] getData = new byte[0];
		try {
			getData = readInputStream(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String content = new String(getData);
		JSONArray data =  JSONObject.parseArray(content);

		return R.ok(data, "获取成功");
	}

	@Override
	public R levelCityes() {
		InputStream is = this.getClass().getClassLoader().getResourceAsStream("cityByLevels.json");
		byte[] getData = new byte[0];
		try {
			getData = readInputStream(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String content = new String(getData);
		JSONArray data =  JSONObject.parseArray(content);

		return R.ok(data, "获取成功");
	}

	@Override
	public R counties() {
		InputStream is = this.getClass().getClassLoader().getResourceAsStream("county.json");
		byte[] getData = new byte[0];
		try {
			getData = readInputStream(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String content = new String(getData);
		JSONArray data =  JSONObject.parseArray(content);

		return R.ok(data, "获取成功");
	}

	@Override
	public R businessDistrict() {
		InputStream is = this.getClass().getClassLoader().getResourceAsStream("business.json");
		byte[] getData = new byte[0];
		try {
			getData = readInputStream(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String content = new String(getData);
		JSONArray data =  JSONObject.parseArray(content);

		return R.ok(data, "获取成功");
	}

	@Override
	public R generateData() {

		//按 规划
		JSONArray result = new JSONArray();
		Integer[] arr = {1, 2, 3, 4, 6};
		for (Integer level : arr){
			JSONObject obj = new JSONObject();
			result.add(obj);
			obj.put("level", level);

			JSONArray cityArr = new JSONArray();
			obj.put("children", cityArr);

			List<ToutiaoDistrict> cities = this.citiesByLevel(level);
			for (ToutiaoDistrict item : cities){
				JSONObject cityOjb = toJSONOjbect(item);
				cityArr.add(cityOjb);
			}
		}

		return R.ok(result);
	}





	private JSONObject toJSONOjbect(ToutiaoDistrict item){
		JSONObject obj = new JSONObject();
		obj.put("id", item.getId());
		obj.put("parent",item.getParent());
		obj.put("level",item.getLevel());
		obj.put("name", item.getName());
		obj.put("proviceCapital", item.getProviceCapital());
		obj.put("cityLevel", item.getCityLevel());

		return obj;
	}

	private static  byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}
}

/*JSONArray result = new JSONArray();
		List<ToutiaoDistrict> provices = this.listByParentId(0, 1);
		for (ToutiaoDistrict province : provices){
			//省份
			JSONObject provinceObj = toJSONOjbect(province);
			result.add(provinceObj);

			//市
			List<ToutiaoDistrict> cities = this.listByParentId(province.getId(), 2);
			JSONArray cityJSONArr = new JSONArray();
			provinceObj.put("children",cityJSONArr);
			for (ToutiaoDistrict city : cities){
				JSONObject cityObj = toJSONOjbect(city);
				cityJSONArr.add(cityObj);

				List<ToutiaoDistrict> counties = this.listByParentId(city.getId(), 3);
				JSONArray countyJSONArr = new JSONArray();
				cityObj.put("children", countyJSONArr);
				for (ToutiaoDistrict county : counties){
					JSONObject countObj = toJSONOjbect(county);
					countyJSONArr.add(countObj);
				}
			}
		}*/

/*
JSONArray result = new JSONArray();
List<ToutiaoDistrict> provices = this.listByParentId(0, 1);
		for (ToutiaoDistrict province : provices){
			//省
			JSONObject provinceObj = toJSONOjbect(province);
			result.add(provinceObj);

			//市
			List<ToutiaoDistrict> cities = this.provinceCapital(province.getId());
			JSONArray cityJSONArr = new JSONArray();
			provinceObj.put("children",cityJSONArr);
			for (ToutiaoDistrict city : cities){
				JSONObject cityObj = toJSONOjbect(city);
				cityJSONArr.add(cityObj);

//商圈
				List<ToutiaoDistrict> counties =  this.listByParentId(city.getId(), 4);     //  this.listByParentId(city.getId(), 3);
				JSONArray countyJSONArr = new JSONArray();
				cityObj.put("children", countyJSONArr);
				for (ToutiaoDistrict county : counties){
					JSONObject countObj = toJSONOjbect(county);
					countyJSONArr.add(countObj);
				}
			}
		}

		*/


/*

		//按 规划
				JSONArray result = new JSONArray();
		Integer[] arr = {1, 2, 3, 4, 6};
		for (Integer level : arr){
			JSONObject obj = new JSONObject();
			result.add(obj);
			obj.put("level", level);

			JSONArray cityArr = new JSONArray();
			obj.put("children", cityArr);

			List<ToutiaoDistrict> cities = this.citiesByLevel(level);
			for (ToutiaoDistrict item : cities){
				JSONObject cityOjb = toJSONOjbect(item);
				cityArr.add(cityOjb);
			}
		}


 */